package application.Service;

import application.Pojo.Failure;
import application.Pojo.Success;
import application.utils.Utils;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Auther: Ohto_Ai
 * @Date: 2022/2/23 - 02 - 23 - 10:07
 * @Description: Service
 *  1.0
 */
@WebServlet(urlPatterns = "/sendborrowapplication")
public class SendBorrowApplication extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");


        //用户名（名字+学号）
        String username = null;

        //借书的日期
        String borrow_date = null;

        //默认借书时长为30天
        int time = 30;

        //书籍id
        String bookid = null;

        //还书日期
        String return_date = null;

        //借书申请数据库的连接、处理、结果对象
        Connection borrowApply = null;
        PreparedStatement bstmt = null;
        ResultSet brs = null;

        //用户数据库的连接、处理、结果对象
        Connection userData = null;
        Statement ustmt = null;
        ResultSet urs = null;

        //书籍信息数据库的连接、处理、结果对象
        Connection bookinformation = null;
        Statement istmt = null;
        ResultSet irs = null;


        try {

            //得到request中的JSON信息
            Utils utils = new Utils();
            JSONObject jsonObject = utils.getJSONObject(req);
            username = jsonObject.getString("username");
            borrow_date = jsonObject.getString("borrow_date");
            time =Integer.parseInt(jsonObject.getString("time"));
            bookid = jsonObject.getString("bookid");


            //定义日期格式，并计算出还书日期，返回成字符串类型
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
            Date date = sdf.parse( borrow_date );

            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_MONTH,+time);
            return_date = sdf.format(rightNow.getTime());

            //连接书籍信息数据库
            bookinformation = utils.JDBCConection("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/apply","root","123456");

            //设置事务不自动提交
            bookinformation.setAutoCommit(false);

            //创建sql语句

            StringBuilder sbisql = new StringBuilder("SELECT id FROM bookinformation WHERE id = \"");
            sbisql.append(bookid);
            sbisql.append("\";");
            String isql = sbisql.toString();

            //集获取书籍信息库结果

            istmt = bookinformation.createStatement();
            irs = istmt.executeQuery(isql);

            //获取数据库中的bookid
            System.out.println(irs);
            String tempbookid = null;
            while(irs.next()){

                tempbookid = irs.getString("id");

                }

            bookid = tempbookid;
            //连接用户数据库
            userData = utils.JDBCConection("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/apply","root","123456");

            //设置事务不自动提交
            userData.setAutoCommit(false);

            //创建sql语句
            StringBuilder sbusql = new StringBuilder("SELECT email,username FROM userdata WHERE username = \"");
            sbusql.append(username);
            sbusql.append("\";");
            String usql = sbusql.toString();
            String email = null;

            //集获用户信息数据库结果
            ustmt = userData.createStatement();
            urs = ustmt.executeQuery(usql);


            //获取用户数据库中的email和username
            while(urs.next()){

                    username = urs.getString("username");
                    email = urs.getString("email");

                }


            //判断用户名是否正确错误返回错误码和信息
            if(username.isEmpty() ){

                //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                Failure failure = new Failure();
                failure.setCode("-1");
                failure.setMessage("账号信息填写错误");

                String json = JSONObject.toJSONString(failure);

                //将json对象转化为字符串在终端输出
                System.out.print(json);

                //把json数据返回给浏览器：
                resp.getWriter().write(json);

                //出现异常事务回滚
                try {
                    bookinformation.rollback();
                    userData.rollback();
                    borrowApply.rollback();
                } catch (SQLException ex) {
                    //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                    Failure rollbackfailure = new Failure();
                    failure.setCode(String.valueOf(ex.getErrorCode()));
                    failure.setMessage(ex.getMessage());

                    String rollbackjson = JSONObject.toJSONString(failure);


                    //将json对象转化为字符串在终端输出
                    System.out.print(rollbackjson);

                    //把json数据返回给浏览器：
                    resp.getWriter().write(rollbackjson);
                }

            }else{
                if ( borrow_date.isEmpty() || time <= 0 || bookid.isEmpty()) {

                    //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                    Failure failure = new Failure();
                    failure.setCode("-1");
                    failure.setMessage("请检查填入的借书日期、书籍id和时间是否正确");

                    String json = JSONObject.toJSONString(failure);

                    //将json对象转化为字符串在终端输出
                    System.out.print(json);

                    //把json数据返回给浏览器：
                    resp.getWriter().write(json);

                    //出现异常事务回滚
                    try {
                        bookinformation.rollback();
                        userData.rollback();
                        borrowApply.rollback();
                    } catch (SQLException ex) {

                        ex.printStackTrace();
                        //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                        Failure rollbackfailure = new Failure();
                        failure.setCode(String.valueOf(ex.getErrorCode()));
                        failure.setMessage(ex.getMessage());

                        String rollbackjson = JSONObject.toJSONString(failure);

                        //将json对象转化为字符串在终端输出
                        System.out.print(rollbackjson);

                        //把json数据返回给浏览器：
                        resp.getWriter().write(rollbackjson);
                    }

                } else {
                    //连接借书申请数据库
                    borrowApply = utils.JDBCConection("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/apply","root","123456");

                    //设置事务不自动提交
                    borrowApply.setAutoCommit(false);

                    String bsql = "INSERT INTO borrowapply(username,bookid,borrow_date,return_date,email,status) VALUES(?,?,?,?,?,?)";

                    bstmt = borrowApply.prepareStatement(bsql);
                    bstmt.setString(1,username);
                    bstmt.setString(2,bookid);
                    bstmt.setString(3,borrow_date);
                    bstmt.setString(4,return_date);
                    bstmt.setString(5,email);
                    bstmt.setString(6,"申请中");


                    bstmt.executeUpdate();

                    //事务提交
                    bookinformation.commit();
                    userData.commit();
                    borrowApply.commit();

                    //返回包含正确访问码和信息的JSON字符串
                    Success success = new Success();
                    success.setCode("200");
                    success.setMessage("申请成功，请等待管理员审批");

                    String json = JSONObject.toJSONString(success);
                    resp.getWriter().write(json);
                }
            }

        } catch (Exception e) {

            e.printStackTrace();
            //捕捉异常并且 返回包含错误码信息对象的JSON字符串
            Failure failure = new Failure();
            failure.setCode("-1");
            failure.setMessage("申请失败！请检查申请信息填写是否正确");

            String json = JSONObject.toJSONString(failure);

            //将json对象转化为字符串在终端输出
            System.out.print(json);

            //把json数据返回给浏览器：
            resp.getWriter().write(json);

            //出现异常事务回滚
            try {
                bookinformation.rollback();
                userData.rollback();
                borrowApply.rollback();
            } catch (SQLException ex) {

                ex.printStackTrace();
                //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                Failure rollbackfailure = new Failure();
                failure.setCode(String.valueOf(ex.getErrorCode()));
                failure.setMessage("申请失败！请检查信息填写是否正确");

                String rollbackjson = JSONObject.toJSONString(failure);

                //将json对象转化为字符串在终端输出
                System.out.print(rollbackjson);

                //把json数据返回给浏览器：
                resp.getWriter().write(rollbackjson);
            }

        }finally {
            try {
                if ( brs != null){
                    brs.close();
                }
                if (bstmt != null){
                    bstmt.close();
                }
                if (borrowApply != null){
                    borrowApply.close();
                }

                if ( urs != null){
                    urs.close();
                }
                if (ustmt != null){
                    ustmt.close();
                }
                if (userData != null){
                    userData.close();
                }
                if ( irs != null){
                    irs.close();
                }
                if (istmt != null){
                    istmt.close();
                }
                if (bookinformation != null){
                    bookinformation.close();
                }

            } catch (SQLException e) {

                e.printStackTrace();
                //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                Failure failure = new Failure();
                failure.setCode(String.valueOf(e.getErrorCode()));
                failure.setMessage(e.getMessage());

                String json = JSONObject.toJSONString(failure);

                //将json对象转化为字符串在终端输出
                System.out.print(json);

                //把json数据返回给浏览器：
                resp.getWriter().write(json);

                //出现异常事务回滚
                try {
                    bookinformation.rollback();
                    userData.rollback();
                    borrowApply.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                    Failure rollbackfailure = new Failure();
                    failure.setCode(String.valueOf(ex.getErrorCode()));
                    failure.setMessage(ex.getMessage());

                    String rollbackjson = JSONObject.toJSONString(failure);

                    //将json对象转化为字符串在终端输出
                    System.out.print(rollbackjson);

                    //把json数据返回给浏览器：
                    resp.getWriter().write(rollbackjson);

                }
            }
        }

    }
}
